<template>
  <div>
    <div v-if="!readonly" style="text-align: right">
      <el-button-group style="margin-top: 0px; margin-right: 12px; margin-bottom: 4px;">
        <el-tooltip content="下一个" placement="top" :open-delay="500">
          <el-button type="primary" icon="el-icon-right" size="mini" @click="next" />
        </el-tooltip>
        <el-tooltip content="编辑" placement="top" :open-delay="500">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="edit" />
        </el-tooltip>
        <el-tooltip content="保存并继续" placement="top" :open-delay="500">
          <el-button type="primary" icon-class="skill" size="mini" @click="saveTestExecute(true)"><svg-icon icon-class="save-continuer" /></el-button>
        </el-tooltip>
        <el-tooltip content="保存" placement="top" :open-delay="500">
          <el-button type="primary" icon-class="skill" size="mini" @click="saveTestExecute(false)"><svg-icon icon-class="save" /></el-button>
        </el-tooltip>
      </el-button-group>
    </div>
    <el-card shadow="hover">
      <el-form v-if="!readonly" ref="testExecuteForm" :rules="rules" :model="form" label-position="left" label-width="80px">
        <el-form-item label="用例状态" prop="status">
          <el-radio-group v-model="form.status" @change="handleChangeStatus">
            <el-radio-button label="4"><i class="el-icon-success" style="color: #67C23A;" /> 通过</el-radio-button>
            <el-radio-button label="3"><i class="el-icon-error" style="color: #F56C6C;" /> 不通过</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :autosize="{ minRows: 3, maxRows: 15 }" placeholder="请输入备注" />
        </el-form-item>
      </el-form>

      <el-descriptions class="margin-top" :column="3" border :label-style="{ width: '100px' }">
        <el-descriptions-item label="用例编号" span="3">{{ element.number }}</el-descriptions-item>
        <el-descriptions-item span="3" label="用例名称">{{ element.name }}</el-descriptions-item>
        <el-descriptions-item label="前提条件">{{ element.before }}</el-descriptions-item>
        <el-descriptions-item label="优先级" :content-style="{ width: '10%' }">P{{ element.priority }}</el-descriptions-item>
      </el-descriptions>

      <el-checkbox-group v-model="failedStepIndex" size="mini">
        <el-table
          ref="stepsTable"
          border
          size="mini"
          :data="tableData"
        >
          <el-table-column type="index" align="center" width="60" label="编号" />
          <el-table-column prop="step" label="操作步骤" min-width="50%">
            <template v-slot="scope">
              {{ scope.row.step }}
            </template>
          </el-table-column>
          <el-table-column prop="result" label="预期结果" min-width="40%">
            <template v-slot="scope">
              {{ scope.row.result }}
            </template>
          </el-table-column>
          <el-table-column v-if="!readonly" align="center" label="操作" width="100">
            <template v-slot="scope">
              <el-checkbox-button :key="scope.$index" :label="scope.$index" @change="changeFailedStepIndex">失败</el-checkbox-button>
            </template>
          </el-table-column>
        </el-table>
      </el-checkbox-group>

      <div v-if="caseRemark && caseRemark.length !== 0" style="font-size: 14px; margin-top: 40px;">评审记录：
        <el-timeline style="margin-top: 10px;">
          <el-timeline-item
            v-for="(item, index) in caseRemark"
            :key="index"
            :color="statusColorMap[item.status]"
            :timestamp="item.updatedAt | parseTime('{y}-{m}-{d} {h}:{i}:{s}')"
          >
            <el-card style="width: 100%;" class="box-card" shadow="never" body-style="padding: 5px">
              <p style="font-size: 13px;">状态： {{ item.status === 3 ? '不通过' : item.status === 4 ? '通过' : '未知' }}</p>
              <p v-if="item.remark !== ''" style="font-size: 13px">备注： {{ item.remark }}</p>
              <div v-if="item.details !== ''" v-html="item.details" />
              <p style="font-size: 13px">评审人： {{ selectName(item.reviewerUserId) }}</p>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-card>
  </div>
</template>

<style lang="scss">
  .item {
    .el-input__inner {
      border: 1px solid #fff !important;
      resize: none;
    }
    .el-textarea__inner {
      border: 1px solid #fff !important;
      resize: none;
    }
  }
</style>
<style>
  .icon-style {
    font-size: 15px;
  }
  .icon-wrapper {
    display: inline-flex;
    align-items: center;
    cursor: pointer;
    color: #606266;
    width: 20px;
    height: 20px;
  }
  .icon-wrapper:hover {
    color: #409EFF;
  }
  .icon-hover {
    color: #409EFF;
  }
  .icon-text {
    margin-left: 5px;
  }
</style>

<script>
import { selectById as testCaseSelectById } from '@/api/functional_test/test_case_manage/test_case'
import { create as create_Remark, getCaseRemark as get_case_remark } from '@/api/functional_test/test_case_manage/review_remark'
import { executePlan as execute_plan } from '@/api/functional_test/test_case_manage/review_execute'
import { selectUserByProjectId } from '@/api/user'

export default {
  props: {
    value: {
      type: Object,
      default() {
        return {
          catalogId: 0, // 分类 id
          textMode: false // 文本模式编辑
        }
      }
    },
    // 是否只读
    readonly: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      radio: null,
      element: {}, // element 对象
      tableData: [],
      statusColorMap: {
        4: 'green',
        3: 'red'
      },
      caseRemark: null,
      form: {
        id: undefined,
        projectId: this.$store.getters.projectId,
        reviewsId: this.$route.query.id,
        // reviewerUserId: ,
        testCaseId: '',
        status: '',
        remark: '',
        details: '',
        operator: this.$store.getters.name
      },
      failedStepIndex: [], // 失败步骤索引 列表
      userList: [], // 执行人列表
      rules: {
        status: [
          { required: true, message: '请选择评审状态', trigger: 'input' }
        ]
      }
    }
  },
  created() {
  },
  methods: {
    // 初始化数据
    resetData() {
      // 恢复 form 数据
      this.form.remark = ''
      this.form.status = ''
      this.form.details = ''

      this.failedStepIndex = [] // 恢复 失败步骤索引 列表
    },
    // 设置 element 数据（当服务端返回数据后有些类型不符需要在这个方法中转换）
    setElement(ele) {
      this.form.testCaseId = ele.id
      this.element = ele
      this.changeToTableMode()
      this.resetData()
    },
    // 装载数据
    loadData(caseId, reviewsId) {
      this.selectUserByProjectId()

      // 装载测试用例
      testCaseSelectById(caseId).then(response => {
        this.setElement(response.data)
      })
      // 装载 remark
      if (reviewsId !== undefined && reviewsId !== null) {
        get_case_remark(reviewsId, caseId).then(response => {
          this.caseRemark = response.data
        })
      }
    },
    // 改变到表格模式
    changeToTableMode() {
      // 将文本按照 \n 分割成数组
      const steps = this.element.steps[0].extra1.trimEnd().split(/[\n]/)
      const results = this.element.steps[0].extra2.trimEnd().split(/[\n]/)

      // 以 steps results 这两最大的当 arrLength
      let arrLength = 0
      steps.length >= results.length ? arrLength = steps.length : arrLength = results.length

      // 遍历 steps results 生成 表格数据
      const tempTableData = []
      for (let i = 0; i < arrLength; i++) {
        const tempRow = {}
        if (steps.length > i) {
          tempRow.step = steps[i]
        } else {
          tempRow.step = ''
        }
        if (results.length > i) {
          tempRow.result = results[i]
        } else {
          tempRow.result = ''
        }
        tempTableData.push(tempRow)
      }

      // 替换原来的表格数据
      this.tableData = tempTableData
    },
    // 失败步骤索引 改变
    changeFailedStepIndex() {
      this.form.status = '4'
    },
    // 保存测试执行结果
    saveTestExecute(saveAndContinue) {
      this.$refs['testExecuteForm'].validate((valid) => {
        if (valid) {
          // 生成 details
          if (this.failedStepIndex.length !== 0) {
            this.form.details = '<style>.mytable { border-collapse: collapse; border: 1px solid #dfe6ec; font-family: "Helvetica", "Arial", sans-serif; font-size: 13px;color: #606266; text-align: left; }</style>' +
              '<table class="mytable" style="width: 90%; margin-left: 0px;">' +
              '<tr class="mytable"><th class="mytable" style="width: 80px; text-align: center;">步骤编号</th><th class="mytable">操作步骤</th><th class="mytable">预期结果</th></tr>'
          }
          for (const item of this.failedStepIndex) {
            this.form.details = this.form.details + '<tr class="mytable"><td class="mytable" style="text-align: center;">' + (item + 1) + '</td><td class="mytable">' + this.tableData[item].step + '</td><td class="mytable">' + this.tableData[item].result + '</td></tr>'
          }
          if (this.failedStepIndex.length !== 0) {
            this.form.details = this.form.details + '</table>'
          }

          // 创建 remark 信息
          create_Remark(this.form).then(response => {
            this.$message({ message: '添加成功!', type: 'success' })
            this.caseRemark.unshift(response.data)
          })

          execute_plan({
            testCaseId: this.form.testCaseId,
            caseStatus: this.form.status,
            reviewsId: this.form.reviewsId
          }).then(response => {
            // 修改树节点状态
            let tmpData
            if (this.form.status === '4') {
              tmpData = { icon: 'pass' }
            } else if (this.form.status === '3') {
              tmpData = { icon: 'fail' }
            }
            if (saveAndContinue) { // 保存并继续
              this.$emit('updateNext', tmpData)
            } else { // 保存
              this.$emit('update', tmpData)
            }

            this.resetData()
          })
        }
      })
    },
    // 下一个 tree 节点
    next() {
      this.$emit('next')
    },
    // 点击 编辑
    edit() {
      window.open('/#/functional_test/test_case?id=' + this.element.id, '_blank')
    },
    // 点击 用例状态
    handleChangeStatus(value) {
      if (value === '4') { // 如果用例状态是 通过，清除 失败步骤索引 列表
        this.failedStepIndex = []
      }
    },
    selectUserByProjectId() { // 通过 projectId 查询对应的 user 信息
      selectUserByProjectId(this.form.projectId).then(response => {
        this.userList = response.data // 将后端返回的值赋给 userList 列表
      })
    },
    selectName(uid) { // 根据 uid 转成用户名称
      for (const user of this.userList) { // 遍历 userList 这个数组 拿到每一组对象
        if (user.id === uid) { // 每一组对象中的 ID 和 uid 进行匹配
          return user.name // 如果匹配，说明找到对应的用户
        }
      }
      return '' // 如果遍历完还没有找到，说明该用户不存在
    }
  }
}
</script>
